package com.sanchunhui.psc.ui.activity

import android.os.Bundle
import android.text.TextUtils
import com.sanchunhui.presenter.ResetPwdPresenter
import com.sanchunhui.presenter.view.ResetPwdView
import com.sanchunhui.psc.R
import com.sanchunhui.psc.common.BaseApplication
import com.sanchunhui.psc.data.protocol.ResponseInfo
import com.sanchunhui.psc.ext.enable
import com.sanchunhui.psc.ext.onClick
import com.sanchunhui.psc.injection.component.DaggerUserComponent
import com.sanchunhui.psc.injection.module.UserModule
import com.sanchunhui.ui.activity.BaseMvpActivity
import kotlinx.android.synthetic.main.activity_login.*
import kotlinx.android.synthetic.main.activity_login.mPwdEt
import kotlinx.android.synthetic.main.activity_reset_pwd.*
import org.jetbrains.anko.clearTop
import org.jetbrains.anko.intentFor
import org.jetbrains.anko.singleTop
import org.jetbrains.anko.toast

/**
 * @Author zyx
 * @Date 2021/7/9-8:52
 * @Dscribe
 */
class ResetPwdActivity : BaseMvpActivity<ResetPwdPresenter>(), ResetPwdView {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_reset_pwd)
        initView()
    }

    /*
        初始化视图
     */
    private fun initView() {

        mConfirmBtn.enable(mOldPwdEt,{isBtnEnable()})
        mConfirmBtn.enable(mNewPwdEt,{isBtnEnable()})

        mConfirmBtn.onClick {
            val user = BaseApplication.mUser
            if (mNewPwdEt.text.length < 6 || mNewPwdEt.text.length > 32 || isNumberOrLetter(mNewPwdEt.text.toString())){
                toast("密码应为6-32位字母或数字")
                return@onClick
            }
            mPresenter.resetPwd(user.token.toString(),mOldPwdEt.text.toString(),mNewPwdEt.text.toString())
        }
    }

    fun isNumberOrLetter(pwdStr: String): Boolean {
        val telRegex = "^[a-zA-Z0-9]"
        if (TextUtils.isEmpty(pwdStr))
            return false
        else
            return pwdStr.matches(telRegex.toRegex())
    }

    /*
        Dagger注册
     */
    override fun injectComponent() {
        DaggerUserComponent.builder().activityComponent(mActivityComponent).userModule(UserModule()).build().inject(this)
        mPresenter.mView = this
    }

    /*
        判断按钮是否可用
     */
    private fun isBtnEnable():Boolean{
        return mOldPwdEt.text.isNullOrEmpty().not() &&
                mNewPwdEt.text.isNullOrEmpty().not()
    }

    /*
        重置密码回调
     */
    override fun onResetPwdResult(result: ResponseInfo) {

        if (result.code == 0) {
            toast("修改密码成功")
            finish()
        } else {
            if (result.message.isNotEmpty()) {
                toast(result.message)
            } else {
                toast("修改密码失败")
            }

        }
//        startActivity(intentFor<LoginActivity>().singleTop().clearTop())
    }
}